#include <Runner.h>
#include <Common/util.h>
#include <VM/vm.h>
#include <iostream>
#include <string>
#include <unordered_set>

VM Runner::vm = VM();
bool Runner::DEBUG = false;

int Runner::runScript(const std::string &filename)
{
    auto content = readfile(filename);
    if (content)
        return runCode(content.value());

    return -1;
}

int Runner::runRepl()
{
    std::string input;
    static std::unordered_set<char> changeLine{';', '{', '}'};

    while (true)
    {
        std::cout << "lox > ";
        std::getline(std::cin, input);
        if (input == "exit")
            return 0;

        if (input.empty())
            continue;

        std::string text = input;
        while (changeLine.find(text.back()) != changeLine.end())
        {
            std::cout << "...   ";
            std::getline(std::cin, input);
            text += "\n" + input;
        }

        runCode(text);
    }

    return 0;
}

int Runner::runCode(std::string_view text)
{
    auto result = vm.interpret(text);
    switch (result)
    {
    case InterpretResult::OK:
        return 0;
    case InterpretResult::COMPILE_ERROR:
        return 1;
    case InterpretResult::RUNTIME_ERROR:
        return 2;
    }

    return -1; // "impossible"
}
